import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from './../views/login/login'
import store from '@/store'
import { Message } from 'element-ui'
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((error) => error)
}
Vue.use(VueRouter)
const canShowUrls = [
  '/main/shelves',
  '/main/audit',
  '/main/personalInfo',
  '/main/mySubscribes'
]
const routes = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: '登录',
    component: Login
  },
  {
    path: '/main',
    name: '首页',
    component: () => import('@/views/main'),
    children: [
      {
        path: '/main',
        redirect: '/main/home'
      },
      {
        path: '/main/home',
        name: '首页',
        component: () => import('@/components/ListPage')
      },
      {
        path: '/main/detail',
        name: '详情',
        component: () => import('@/views/DetailPage')
      },
      {
        path: '/main/mySubscribes',
        name: '我的订阅',
        component: () => import('@/views/Mysubscribes')
      },
      {
        path: '/main/personalInfo',
        name: '发布列表',
        component: () => import('@/views/PersonalInfo')
      },
      {
        path: '/main/shelves',
        name: '上架',
        component: () => import('@/views/Shelves')
      },
      {
        path: '/main/audit',
        name: '审核列表',
        component: () => import('@/views/Audit')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
const findRoute = (routes, toFind, arr = []) => {
  for (const item of routes) {
    if (item.path === toFind) {
      return arr.concat([item.name, item.path])
    }
    if (item.children) {
      arr.push(...[item.name, item.path])
      return [].concat(findRoute(item.children, toFind, arr))
    }
  }
}
const formatRoute = (breadCrumb) => {
  const retObj = {}
  for (let i = 0; i < breadCrumb.length; i++) {
    i % 2 === 1 && (retObj[breadCrumb[i - 1]] = breadCrumb[i])
  }
  return retObj
}
router.beforeEach((to, from, next) => {
  const { path } = to
  const allFlattedRoutes = routes.flat(Infinity)
  const breadCrumb = findRoute(allFlattedRoutes, path)
  const breadCrumbObj = formatRoute(breadCrumb)
  store.state.pathObj = breadCrumbObj
  store.commit('home/setCanShow', canShowUrls.includes(path))
  if (path === '/main/audit') {
    if (!store.state.login.loginInfo.roleList) {
      router.push('/main')
    } else {
      if (store.state.login.loginInfo.roleList[0].roleCode !== '系统管理员') {
        router.push({ path: '/main' })
        Message({
          message: '无权访问',
          type: 'warning',
          duration: 2000
        })
      } else {
        next()
      }
    }
  } else {
    next()
  }
})
export default router
